package com.kevin.chat;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import lombok.Data;

import org.directwebremoting.Browser;
import org.directwebremoting.Container;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.extend.ScriptSessionManager;
import org.directwebremoting.proxy.dwr.Util;

/**
 * 处理聊天相关
 * 
 * @author lhq
 * 
 */
public class ChatManager {

	/**
	 * 更新在线用户列表
	 * @param username 待添加到列表的用户名
	 * @param flag 是添加用户到列表,还是只获得当前列表
	 * @param request
	 * @return 用户userid
	 */
	@Deprecated
	public String updateUsersList(String username, boolean flag, HttpServletRequest request) {
		if (flag) {	
			//保存用户到列表
			UserManager.addUser(request.getSession().getId(), username);
			//将用户id和页面脚本session绑定
			this.setScriptSessionFlag(request.getSession().getId());
		}
		//获得DWR上下文
		ServletContext sc = request.getSession().getServletContext();
		ServerContext sctx = ServerContextFactory.get(sc);
		//获得当前浏览 index.jsp 页面的所有脚本session
		Collection sessions = sctx.getScriptSessionsByPage("/sysintework/index.jsp");
		Util util = new Util(sessions);
		//处理这些页面中的一些元素
		util.removeAllOptions("users");
		util.addOptions("users", UserManager.getUser(), "username");
		util.removeAllOptions("receiver");
		util.addOptions("receiver", UserManager.getUser(),"userid","username");
		if(!flag){
			return null;
		}
		return request.getSession().getId();
	}
	/**
	 * 更新在线用户列表
	 * @param username 待添加到列表的用户名
	 * @param flag 是添加用户到列表,还是只获得当前列表
	 * @param request
	 * @return 用户userid
	 */
	public String updateUsersList(String id,String username, boolean flag, HttpServletRequest request) {
		if (flag) {	
			//保存用户到列表
			UserManager.addUser(request.getSession().getId(), username);
			//将用户id和页面脚本session绑定
			this.setScriptSessionFlag(request.getSession().getId());
		}
//		//获得DWR上下文
//		ServletContext sc = request.getSession().getServletContext();
//		ServerContext sctx = ServerContextFactory.get(sc);
//		//获得当前浏览 index.jsp 页面的所有脚本session
//		Collection sessions = sctx.getScriptSessionsByPage("/sysintework/index.jsp");
//		Util util = new Util(sessions);
//		//处理这些页面中的一些元素
//		util.removeAllOptions("users");
//		util.addOptions("users", users, "username");
//		util.removeAllOptions("receiver");
//		util.addOptions("receiver", users,"userid","username");
		//3.0
		Browser.withCurrentPage(new Runnable() {
		    public void run() {
		    	org.directwebremoting.ui.dwr.Util.removeAllOptions("users");
		    	org.directwebremoting.ui.dwr.Util.addOptions("users", UserManager.getUser(), "username");
				org.directwebremoting.ui.dwr.Util.removeAllOptions("receiver");
				org.directwebremoting.ui.dwr.Util.addOptions("receiver", UserManager.getUser(),"userid","username");
		    }
		});
		if(!flag){
			return null;
		}
		return request.getSession().getId();
	}

	/**
	 * 将用户id和页面脚本session绑定
	 * @param userid
	 */
	public void setScriptSessionFlag(String userid) {
		WebContextFactory.get().getScriptSession().setAttribute("userid", userid);
	}

	/**
	 * 根据用户id获得指定用户的页面脚本session
	 * @param userid
	 * @param request
	 * @return
	 */
	@Deprecated
	public ScriptSession getScriptSession(String userid, HttpServletRequest request) {
		ScriptSession scriptSessions = null;
		Collection<ScriptSession> sessions = new HashSet<ScriptSession>();
		sessions.addAll(ServerContextFactory.get(request.getSession().getServletContext())
				.getScriptSessionsByPage("/sysintework/index.jsp"));
//		Map<String, ScriptSession> scriptSessionMap = ScriptSessionListenerImp.getScrSessMap();
//		Set<String> keySet = scriptSessionMap.keySet();
//		for(String keyStr:keySet){
//			ScriptSession session = scriptSessionMap.get(keyStr);
//			String xuserid = (String) session.getAttribute("userid");
//			if (xuserid != null && xuserid.equals(userid)) {
//				scriptSessions = session;
//			}
//		}
		for (ScriptSession session : sessions) {
			String xuserid = (String) session.getAttribute("userid");
			if (xuserid != null && xuserid.equals(userid)) {
				scriptSessions = session;
			}
		}
		return scriptSessions;
	}
	
	/**
	 * 发送消息
	 * @param sender 发送者
	 * @param receiverid 接收者id
	 * @param msg 消息内容
	 * @param request
	 */
	public void send(String url,String sender,final String receiverid,String msg,final int pub,HttpServletRequest request){
//		ScriptSession session = this.getScriptSession(receiverid, request);
		//org.directwebremoting.proxy.dwr.Util;
//		Util util = new Util(session);
//		util.setStyle("showMessage", "display", "block");
//		util.setValue("sender", sender);
//		util.setValue("msg", msg);
		Browser.withPageFiltered(url, new ScriptSessionFilter(){

			public boolean match(ScriptSession arg0) {
				// TODO Auto-generated method stub
				if(pub == 0){//私聊
					if(arg0.getAttribute("userid").equals(receiverid))
						return true;
					return false;					
				}else{//公开
					return true;
				}
			}
			
		}, new SendMessageThread(sender,msg));
	}
	@Data class SendMessageThread implements Runnable{
		private String clientMsg;
		private String sender;
		public SendMessageThread(String sender,String msg) {
			this.sender = sender;
			this.clientMsg = msg;
			// TODO Auto-generated constructor stub
		}

		public void run() {
			// TODO Auto-generated method stub
//			ScriptSessions.addFunctionCall("appendMessage",clientMsg);
			org.directwebremoting.ui.dwr.Util.setStyle("showMessage", "display", "block");
			org.directwebremoting.ui.dwr.Util.setValue("sender", sender);
			org.directwebremoting.ui.dwr.Util.setValue("msg", clientMsg);
		}
		
	}
	public void init(){
		

	}
}
